<template>
  <div class="user-management">
    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input 
            v-model="filters.username" 
            placeholder="请输入用户名"
            allow-clear
            @change="loadUsers"
          />
        </a-col>
        <a-col :span="6">
          <a-input 
            v-model="filters.real_name" 
            placeholder="请输入真实姓名"
            allow-clear
            @change="loadUsers"
          />
        </a-col>
        <a-col :span="4">
          <a-select 
            v-model="filters.isadmin" 
            placeholder="用户类型"
            allow-clear
            @change="loadUsers"
          >
            <a-option :value="0">普通用户</a-option>
            <a-option :value="1">管理员</a-option>
          </a-select>
        </a-col>
        <a-col :span="8">
          <a-space>
            <a-button type="primary" @click="loadUsers">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="resetFilters">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>
    
    <!-- 用户表格 -->
    <a-table 
      :data="filteredUsers" 
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @page-size-change="handlePageSizeChange"
    >
      <template #columns>
        <a-table-column title="ID" data-index="id" :width="60" />
        <a-table-column title="用户名" data-index="username" :width="120" />
        <a-table-column title="密码" data-index="password" :width="120">
          <template #cell="{ record }">
            <div class="password-cell">
              <span v-if="!record.showPassword" class="password-mask">
                {{ '•'.repeat(Math.min(record.password?.length || 6, 8)) }}
              </span>
              <span v-else class="password-text">{{ record.password }}</span>
              <a-button 
                type="text" 
                size="mini" 
                @click="togglePassword(record)"
                class="password-toggle"
              >
                <template #icon>
                  <IconEye v-if="!record.showPassword" />
                  <IconEyeInvisible v-else />
                </template>
              </a-button>
            </div>
          </template>
        </a-table-column>
        <a-table-column title="真实姓名" data-index="real_name" :width="120" />
        <a-table-column title="年龄" data-index="age" :width="80">
          <template #cell="{ record }">
            {{ record.age || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="性别" data-index="gender" :width="80">
          <template #cell="{ record }">
            {{ record.gender || '-' }}
          </template>
        </a-table-column>
        <a-table-column title="用户类型" data-index="isadmin" :width="100">
          <template #cell="{ record }">
            <a-tag :color="record.isadmin ? 'red' : 'blue'">
              {{ record.isadmin ? '管理员' : '普通用户' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="当前进度" data-index="allow_node" :width="120">
          <template #cell="{ record }">
            <div v-if="!record.isadmin" class="progress-cell">
              <span>第{{ record.allow_node }}章</span>
              <a-progress 
                :percent="(record.allow_node / 5) * 100" 
                size="mini"
                :show-text="false"
                class="progress-mini"
              />
            </div>
            <span v-else class="admin-text">管理员</span>
          </template>
        </a-table-column>
        <a-table-column title="注册时间" data-index="created_at" :width="160">
          <template #cell="{ record }">
            {{ formatDate(record.created_at) }}
          </template>
        </a-table-column>
        <a-table-column title="操作" :width="80">
          <template #cell="{ record }">
            <a-space v-if="!record.isadmin">
              <a-button type="text" size="small" status="danger" @click="deleteUser(record)">
                <template #icon>
                  <IconDelete />
                </template>
              </a-button>
            </a-space>
            <span v-else class="admin-text">-</span>
          </template>
        </a-table-column>
      </template>
    </a-table>
    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconDelete, IconSearch, IconEye, IconEyeInvisible } from '@arco-design/web-vue/es/icon'
import { userApi } from '../../api'

const loading = ref(false)
const users = ref<any[]>([])
const allUsers = ref<any[]>([])

const filters = reactive({
  username: '',
  real_name: '',
  isadmin: undefined as number | undefined
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
})

const filteredUsers = computed(() => {
  let result = allUsers.value
  
  if (filters.username) {
    result = result.filter(user => 
      user.username.toLowerCase().includes(filters.username.toLowerCase())
    )
  }
  
  if (filters.real_name) {
    result = result.filter(user => 
      user.real_name?.toLowerCase().includes(filters.real_name.toLowerCase())
    )
  }
  
  if (filters.isadmin !== undefined) {
    result = result.filter(user => user.isadmin === filters.isadmin)
  }
  
  return result
})

const resetFilters = () => {
  filters.username = ''
  filters.real_name = ''
  filters.isadmin = undefined
  pagination.current = 1
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await userApi.getUsers()
    if (response.success) {
      // 为每个用户添加showPassword状态
      const usersWithPasswordState = response.data.map((user: any) => ({
        ...user,
        showPassword: false
      }))
      allUsers.value = usersWithPasswordState
      users.value = usersWithPasswordState
      pagination.total = usersWithPasswordState.length
    } else {
      Message.error(response.message || '加载用户失败')
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    Message.error('加载用户失败')
  } finally {
    loading.value = false
  }
}

const togglePassword = (record: any) => {
  record.showPassword = !record.showPassword
}

const deleteUser = (user: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户"${user.real_name || user.username}"吗？此操作不可恢复。`,
    onOk: async () => {
      try {
        const response = await userApi.deleteUser(user.id)
        if (response.success) {
          Message.success('用户删除成功')
          await loadUsers()
        } else {
          Message.error(response.message || '删除用户失败')
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        Message.error('删除用户失败')
      }
    }
  })
}


const handlePageChange = (page: number) => {
  pagination.current = page
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 24px;
}

.filter-section {
  background: white;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 16px;
  border: 1px solid #e5e6eb;
}

.progress-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.progress-mini {
  width: 60px;
}

.admin-text {
  color: #86909c;
  font-size: 12px;
}

.password-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.password-mask {
  font-family: 'Arial', sans-serif;
  letter-spacing: 2px;
  color: #86909c;
  font-size: 14px;
}

.password-text {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  color: #1d2129;
  background: #f7f8fa;
  padding: 2px 6px;
  border-radius: 4px;
  border: 1px solid #e5e6eb;
}

.password-toggle {
  padding: 2px 4px;
  color: #86909c;
  transition: color 0.3s ease;
}

.password-toggle:hover {
  color: #165dff;
}


:deep(.arco-table) {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.arco-table-th) {
  background: #f7f8fa;
  font-weight: 600;
}

:deep(.arco-card) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
